package com.yanqu.road.task;

import com.yanqu.road.server.manger.ForbiddenIpMgr;
import com.yanqu.road.utils.executor.GeneralTask;
import io.netty.util.internal.PlatformDependent;

import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicLong;

public class DirectMemoryMonitorTask extends GeneralTask {
    private static long maxValue;

    @Override
    public void doRun() {
        try {
            Class<PlatformDependent> clazz = PlatformDependent.class;
            Field memoryCounter = clazz.getDeclaredField("DIRECT_MEMORY_COUNTER");
            memoryCounter.setAccessible(true);
            Field memoryLimit = clazz.getDeclaredField("DIRECT_MEMORY_LIMIT");
            memoryLimit.setAccessible(true);
            long nowValue = ((AtomicLong) memoryCounter.get(clazz)).longValue() / 1024 / 1024;
            Long limitValue = (Long) memoryLimit.get(clazz);
            if (nowValue > maxValue) {
                maxValue = nowValue ;
            }
            getLOGGER().info("memory limit is {} M, now is {} M, max is {} M", limitValue / 1024 / 1024, nowValue, maxValue);
            ForbiddenIpMgr.upload();
        } catch (Exception e) {
            getLOGGER().error("DirectMemoryMonitorTask run error.", e);
        }
    }
}
